<template>
  <div class="app-container2">
    <div class="left_box">
      <commonTree2 :treeData="treeData" :currentId="currentDeviceCode" :defaultProps="defaultProps"
        @clickNodeEmitFn="treeClick" />
    </div>
    <div class="right-box">
      <div class="item1">
        <div class="item-left">
          <el-form inline>
            <el-form-item label="预测模型类型">
              <el-select class="js_common_select" :popper-append-to-body="false" placeholder="请选择" v-model="modelType">
                <el-option label="基于可靠度预测模型" value="reliable"></el-option>
                <el-option label="基于健康度预测模型" value="health"></el-option>
              </el-select>
            </el-form-item>
          </el-form>
        </div>
        <div class="item-right">
          <el-button class="js_common_btn" @click="searchBtnwh">预测模型维护</el-button>
          <el-button class="js_common_btn" @click="searchBtn">建模数据查询</el-button>
          <el-button class="js_common_btn" @click="importBtn">建模样本导入</el-button>
        </div>
      </div>
      <div class="item2">
        <EasyTable v-if="colsData.length" :colsData="colsData" :tableData="tableData"></EasyTable>
        <div class="no_data" v-else>暂无数据</div>
      </div>
      <div class="item3">
        <el-form inline class="left_form">
          <el-form-item label="模型创建算法">
            <el-select class="js_common_select" :popper-append-to-body="false" placeholder="请选择"
              v-model="form2.arithType">
              <el-option v-for="(item, idx) in dict.type.arit_type" :key="idx" :value="item.label"
                :label="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button class="js_common_btn" @click="createModelBtn" :disabled="creating">预测模型生成</el-button>
          </el-form-item>
          <!-- <el-form-item>
            <el-button class="js_common_btn" @click="">模型偏差分析</el-button>
          </el-form-item> -->
          <!-- <el-form-item label="平均偏差:">
            <span class="num_box"> {{ form2.meanVariation }} </span>
          </el-form-item>
          <el-form-item label="拟合度:">
            <span class="num_box"> {{ form2.degreeFitting }} </span>
          </el-form-item> -->
        </el-form>
        <div class="right_div">
          <span class="title"> 平均偏差:</span><span class="num_box"> {{ form2.meanVariation }} </span>
          <span class="title"> 拟合度:</span><span class="num_box"> {{ form2.degreeFitting }} </span>
          <el-button class="js_common_btn right_btn" @click="forecastModelBasic">预测模型保存</el-button>
        </div>
      </div>
      <div class="item4">
        <div class="item4-left">
          <div class="title" style="color: #1f2d3d">故障预测模型</div>
          <div class="descriptions_wrapper">
            <el-descriptions :column="1">
              <el-descriptions-item v-for="(val, key) in jsonData" :key="key" :label="key">{{ val
                }}</el-descriptions-item>
            </el-descriptions>
          </div>
        </div>
        <div class="item4-right">
          <lineCharts :echartsData="chartsData" />
        </div>
      </div>
      <searchDialog v-if="dialogVisible1" :deviceCode="currentDeviceCode" :deviceTypeCode="currentDeviceTypeCode"
        :type="modelType" @confirm="confirm1" @close="close1" @syncData="syncData"></searchDialog>
      <!-- 建模样本导入弹窗 -->
      <importDataDialog v-if="dialogVisible2" @confirm="confirm2" @close="close2"></importDataDialog>
    </div>
    <el-dialog class="jk_common_dialog000" title="预测模型命名" :visible.sync="nameDialogVisible" width="30%" append-to-body
      @close="nameDialogClose">
      <div class="content-box">
        <el-form ref="nameForm" :model="nameForm" :rules="nameRules" label-width="100px">
          <el-form-item label="模型名称" prop="name">
            <el-input class="js_common_input2" v-model="nameForm.name" placeholder="请输入模型名称"></el-input>
          </el-form-item>
          <el-form-item label="模型描述" prop="desp">
            <el-input class="js_common_input2" v-model="nameForm.desp" placeholder="请输入模型描述"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :disabled="false" @click="nameDialogConfirm">确 定</el-button>
        <el-button @click="nameDialogClose">取 消</el-button>
      </div>
    </el-dialog>
    <el-dialog class="jk_common_dialog000" title="预测模型维护" :visible.sync="whDialogVisible" width="60%" append-to-body
               @close="nameDialogClose">
      <div class="content-box">
        <div class="right_main_box1" >
          <el-table ref="modelTable" class="jk_common_table004" :data="modelData" height="400" border
                    style="width: 100%; height: 100%" >
            <el-table-column type="index" width="55" label="序号" align="center" />
            <el-table-column v-for="(item, i) in modelColumn" :key="i" :label="item.label" :prop="item.prop" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleDelete(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

      </div>
      <div slot="footer" class="dialog-footer">
<!--        <el-button type="primary" :disabled="false" @click="nameDialogConfirm">确 定</el-button>-->
        <el-button @click="whDialogClose">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog  title="多元非线性回归配置" :visible.sync="dyDialogVisible" width="50%" append-to-body
               @close="dyDialogClose">
      <div class="content-box">
        <div class="right_main_box1" >
          <el-table ref="dyTable" class="jk_common_table004" :data="dyData" height="500" border
                    style="width: 100%; height: 100%">
            <el-table-column type="index" width="55" label="序号" align="center" />
            <el-table-column label="操作变量名称" prop="label" width="400" align="center"/>
            <el-table-column label="基函数类型" prop="func"  align="center">
              <template v-slot="scope">
                <el-select v-model="scope.row.func" size="mini" style="width: 100%;">
                  <el-option v-for="(option, i) in funcOptions" :key="i" :label="option" :value="option">
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="参数值" prop="num" align="center">
              <template v-slot="scope">
                <el-input v-model="scope.row.num" size="mini" type="number"  style="width: 100%;" />
              </template>
            </el-table-column>
          </el-table>
        </div>

      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dyConfirm">确 定</el-button>
        <el-button @click="dyDialogClose">关 闭</el-button>
      </div>
    </el-dialog>

  </div>
</template>
<script>
import commonTree2 from "@/components/commonTree2";
import EasyTable from "@/components/CommonTable/EasyTable";
import lineCharts from "./lineCharts.vue";

import searchDialog from "./searchDialog";
import importDataDialog from "./importDialog";
import * as api from "@/api/myApi/yc_chuangjian";
import {forecastModelBasic, getFactorList,delModelBasic} from "@/api/myApi/healthEvaluate";
import tableTooltip from "@/components/TableTooltip/index.vue";
import {createForecastModelDataNonLine} from "@/api/myApi/yc_chuangjian";

export default {
  name: "",
  components: {
    tableTooltip,
    commonTree2,
    EasyTable,
    lineCharts,
    searchDialog,
    importDataDialog,
  },
  props: {
    data: {
      type: Array,
      default: () => [],
    },
  },
  dicts: ["arit_type"],
  data() {
    return {
      modelColumn: [
        // { label: "名称", prop: "deviceName" },
        // {label: '设备类型', prop: 'key'},
        { label: "模型名称", prop: "modelName" },
        { label: "创建日期", prop: "createTime" },
        { label: "创建用户", prop: "createBy" },
      ],
      dyColumn:[

      ],
      modelData: [],
      dyData:[],
      defaultProps: {
        children: "children",
        label: "name",
      },
      // func下拉框的选项
      funcOptions: ['幂函数|pow(x, α)', '指数函数|exp(β * x)', '指数函数|exp(β / x)', '对数函数|logα(x)'],
      currentDeviceName: "",
      currentDeviceCode: "",
      currentDeviceTypeCode: "",
      modelType: "",
      tableData: [],
      colsData: [],
      form2: {
        arithType: "",
        meanVariation: "",
        degreeFitting: "",
      },
      jsonData: {
        // "设备名称": "传输带设备",
        // "拟合曲线": "222",
        // "拟合度": "0.8793",
        // "平均偏差": "0.88",
      },
      creating: false,
      chartsData: {
        xData: [],
        yData1: [],
        yData2: [],
        y1Name: '实际值',
        y2Name: '预测值',
        // xData: ['2024-05-01', '2024-05-02', '2024-05-03', '2024-05-04', '2024-05-05', '2024-05-06',],
        // yData1: [4, 5, 6, 7, 8, 9],
        // yData2: [1, 2, 3, 4, 5, 6],
      },
      dialogVisible1: false,
      dialogVisible2: false, // 命名弹窗

      nameDialogVisible: false,
      whDialogVisible:false,
      dyDialogVisible:false,
      nameForm: {
        name: "",
        desp: "",
      },
      nameRules: {
        name: [
          {
            required: true,
            message: "请输入名称",
            trigger: "blur",
          },
        ],
      },
    };
  },

  computed: {
    treeData: function () {
      return this.$store.getters.deviceTree
        ? [this.$store.getters.deviceTree]
        : [];
    },
  },
  methods: {
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id;
      const name = row.modelName || ''
      this.$modal
          .confirm('是否确认删除模型名称为"' + name + '"的数据项？')
          .then(function () {
            return delModelBasic(ids);
          })
          .then(() => {
            this.queryMODEL();
            this.$modal.msgSuccess("删除成功");
          })
          .catch(() => {});
    },
    treeClick(cell) {
      // console.log(cell);
      if (cell.type) {
        this.currentDeviceName = cell.name;
        this.currentDeviceCode = cell.code;
        this.currentDeviceTypeCode = cell.type;
      }
      // 清除表格等数据
      this.tableData = [];
      this.colsData = [];
      this.jsonData = "";
      this.form2 = { arithType: "", meanVariation: "", degreeFitting: "" };
      // this.modelType = "";
    },
    searchBtn() {
      if (this.currentDeviceCode && this.modelType) {
        this.dialogVisible1 = true;
      } else {
        this.$modal.msgWarning("请先选择设备及预测模型类型");
      }
    },
    searchBtnwh(){
      if (this.currentDeviceCode) {
        this.queryMODEL()
        this.whDialogVisible = true;
      } else {
        this.$modal.msgWarning("请先选择设备");
      }
    },
    queryMODEL(){
      forecastModelBasic({deviceCode: this.currentDeviceCode}).then((res) => {
        if (res.code == "200") {
          this.modelData = res.rows;
        }
      });
    },
    importBtn() {
      if (this.currentDeviceCode && this.modelType) {
        this.dialogVisible2 = true;
      } else {
        this.$modal.msgWarning("请先选择设备及预测模型类型");
      }
    },
    // 弹窗导入
    syncData(val) {
      console.log(val);
      this.tableData = val.tableData;
      this.colsData = val.tableName;
    },

    // 命名弹窗
    nameDialogConfirm() {
      this.$refs.nameForm.validate((valid) => {
        if (valid) {
          api
            .forecastModelBasic({
              details: {
                deviceCode: this.currentDeviceCode,
                deviceName: this.currentDeviceName,
                deviceTypeCode: this.currentDeviceCode,
                forecastJson: JSON.stringify(this.jsonData),
                meanVariation: this.form2.meanVariation,
                degreeFitting: this.form2.degreeFitting,
              },
              modelDesp: this.form.desp,
              modelName: this.form.name,
              modelType: this.form2.arithType,
            })
            .then((res) => {
              if (res.code == 200) {
                this.$modal.msgSuccess("保存成功");
                this.nameDialogVisible = false;
              }
            });
        } else {
          return false;
        }
      });
    },
    nameDialogClose() {
      this.nameDialogVisible = false;
      this.$refs.nameForm.resetFields();
    },
    dyDialogClose() {
      this.dyDialogVisible = false;
    },
    whDialogClose() {
      this.whDialogVisible = false;
      this.$refs.nameForm.resetFields();
    },
    nameDialogConfirm() {
      this.$refs.nameForm.validate((valid) => {
        if (valid) {
          api
            .forecastModelBasic({
              details: {
                deviceCode: this.currentDeviceCode,
                deviceName: this.currentDeviceName,
                deviceTypeCode: this.currentDeviceCode,
                forecastJson: JSON.stringify(this.jsonData),
                meanVariation: this.form2.meanVariation,
                degreeFitting: this.form2.degreeFitting,
              },
              modelDesp: this.nameForm.desp,
              modelName: this.nameForm.name,
              modelType: this.modelType,
            })
            .then((res) => {
              if (res.code == 200) {
                this.$modal.msgSuccess(res.msg);
                this.nameDialogClose();
              }
            });
        }
      });
    },
    dyConfirm(){
      // 确保每一行的 func 和 num 都不为空
      let func = this.dyData.every(item => item.func);
      let num = this.dyData.every(item => item.num);

      if (!func || !num) {
        this.$modal.msgWarning("奇函数类型和参数值有未填项，请检查！");
        return;
      }else {
        this.creating = true;
        this.$modal.loading("正在创建模型，请稍候");
        api
            .createForecastModelDataNonLine(this.dyData)
            .then((res) => {
              if (res.code == 200) {
                this.$modal.msgSuccess(res.msg);
                this.form2.meanVariation = res.data.meanVariation;
                this.form2.degreeFitting = res.data.degreeFitting;
                this.jsonData = JSON.parse(res.data.jsonData);

                this.chartsData.y1Name = `${this.modelType == "reliable" ? '可靠度' : '健康度'}实际值`;
                this.chartsData.y2Name = `${this.modelType == "reliable" ? '可靠度' : '健康度'}预测值`;

                this.chartsData.xData = res.data.echartData.x;
                this.chartsData.yData1 = res.data.echartData.y1;
                this.chartsData.yData2 = res.data.echartData.y2;
              }
            })
            .catch((err) => {
              console.log(err);
            })
            .finally(() => {
              this.creating = false;
              this.dyDialogVisible = false;
              this.$modal.closeLoading();
            });
      }
    },
    createModelBtn() {
      if (this.form2.arithType) {
        if(this.form2.arithType == "1") {
          if(this.colsData.length>0){
            // 复制colsData，去掉前两个元素
            const colsWithoutFirstTwo = [...this.colsData].slice(2); // 使用spread操作符复制数组
            this.dyData = colsWithoutFirstTwo.map(col => ({
              prop:col.prop,
              label: col.label, // 对应第一列名称
              func: '',         // 默认func为空，或者可以填充下拉选项
              num: ''           // 默认num为空
            }));
            this.dyDialogVisible = true;

          }else{
            this.$modal.msgWarning("请先建模数据查询");
          }
          return;
        }
        this.creating = true;
        this.$modal.loading("正在创建模型，请稍候");
        api
          .createForecastModelData({
            arithType: this.form2.arithType,
          })
          .then((res) => {
            if (res.code == 200) {
              this.$modal.msgSuccess(res.msg);
              this.form2.meanVariation = res.data.meanVariation;
              this.form2.degreeFitting = res.data.degreeFitting;
              this.jsonData = JSON.parse(res.data.jsonData);

              this.chartsData.y1Name = `${this.modelType == "reliable" ? '可靠度' : '健康度'}实际值`;
              this.chartsData.y2Name = `${this.modelType == "reliable" ? '可靠度' : '健康度'}预测值`;

              this.chartsData.xData = res.data.echartData.x;
              this.chartsData.yData1 = res.data.echartData.y1;
              this.chartsData.yData2 = res.data.echartData.y2;
            }
          })
          .catch((err) => {
            console.log(err);
          })
          .finally(() => {
            this.creating = false;
            this.$modal.closeLoading();
          });
      }
    },
    // 保存按钮
    forecastModelBasic() {
      if (this.jsonData) {
        this.nameDialogVisible = true;
      } else {
        this.$modal.msgWarning("请先生产预测模型");
      }
    },
    confirm1() { },
    close1() {
      this.dialogVisible1 = false;
    },
    confirm2(list) {

      this.tableData = [];
      this.colsData = [];
      const formData = new FormData();
      formData.append("file", list[0].raw);
      formData.append("deviceCode", this.currentDeviceCode);
      this.$modal.loading("正在导入数据，请稍候")
      api.importInitData(formData).then((res) => {
        if (res.code == 200) {
          this.$modal.msgSuccess(res.msg);
          this.dialogVisible2 = false;
          this.tableData = res.data.tableData;
          this.colsData = res.data.tableName;
        }
      }).finally(() => {
        this.$modal.closeLoading();
      });
    },
    close2() {
      this.dialogVisible2 = false;
    },
  },
  created() { },
  mounted() {
    if (!this.$store.getters.deviceTree) {
      this.$store.dispatch("getDeviceTree").then((deviceId) => {
        // this.currentDeviceCode = deviceId;
      });
    }
  },
};
</script>
<style lang="scss" scoped>
.app-container2 {
  width: 100%;
  display: flex;
  height: 100%;
  box-sizing: border-box;
}

.left_box {
  flex: 0 0 auto;
}

.right-box {
  width: 0;
  height: 100%;
  flex: 1;
  margin-left: 10px;
  padding: 20px;
  box-sizing: border-box;
  background: transparent;
  //background: linear-gradient(180deg,
  //    rgba(21, 52, 104, 0.3) 0%,
  //    rgba(12, 29, 57, 0.3) 100%);
  display: flex;
  flex-direction: column;

  .item1 {
    // height: 80px;
    flex: 0 0 auto;
    display: flex;
    align-items: center;
    justify-content: space-between;
    align-items: center;

    ::v-deep .el-form--inline .el-form-item {
      margin-bottom: 0;
    }

  }

  .item3 {
    display: flex;

    .left_form {
      width: calc(50% + 10px);
      margin-right: 5px;
      display: inline-flex;
      align-items: center;
      justify-content: space-between;

      .el-form-item {
        margin-bottom: 0 !important;
      }
    }

    .right_div {
      flex: 1;
      display: inline-flex;
      align-items: center;

      .title {
        color: #000000;
        font-size: 14px;
        font-weight: 600;
        margin-right: 10px;
      }

      .num_box {
        display: inline-block;
        width: 120px;
        height: 30px;
        line-height: 30px;
        padding: 0px 10px;
        border: 1px solid #2e82af;
        color: #000000;
        margin-right: 20px;
      }

      .right_btn {
        margin-left: auto;
      }
    }


  }

  .item2,
  .item4 {
    height: 50px;
    flex: 1 1 auto;
    margin: 10px 0;

    div.no_data {
      width: 100%;
      height: 100%;
      border: 1px solid #2e82af;
      display: flex;
      justify-content: center;
      align-items: center;
      color: #cbcbcb;
    }
  }

  .item4 {
    display: flex;
    justify-content: space-between;

    .item4-left,
    .item4-right {
      padding: 10px;
      height: 100%;
      border: 1px solid #2e82af;
    }

    .item4-left {
      display: flex;
      flex-direction: column;
      font-size: 16px;

      .title {
        color: #fff;
        line-height: 20px;
        text-align: right;
      }

      .descriptions_wrapper {
        flex: 1;
        overflow: auto;

        ::v-deep .el-descriptions {
          .el-descriptions__header {
            color: #fff;
          }

          .el-descriptions__body {
            font-size: 16px;
            background-color: transparent;
            color: #000000;
            font-weight: 700;
          }
        }
      }
    }

    .item4-left {
      width: 50%;
    }

    .item4-right {
      width: calc(50% - 10px);
    }
  }
}
</style>
